import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:location_test/app/presentation/controllers/upload_history_controller.dart';

class UploadHistoryView extends GetView<UploadHistoryController> {
  const UploadHistoryView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('MQTT 上传历史'),
        actions: [
          IconButton(
            icon: const Icon(Icons.delete_sweep_outlined),
            tooltip: '清空所有历史记录',
            onPressed: () => _showClearConfirmationDialog(),
          ),
        ],
      ),
      body: Obx(
        () {
          if (controller.uploadHistory.isEmpty) {
            return const Center(
              child: Text(
                ' 暂无上传记录。\n数据将在成功发送后显示在这里。',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.grey),
              ),
            );
          }
          return ListView.builder(
            itemCount: controller.uploadHistory.length,
            itemBuilder: (context, index) {
              final item = controller.uploadHistory[index];
              return _buildHistoryTile(item);
            },
          );
        },
      ),
    );
  }

  Widget _buildHistoryTile(Map<String, dynamic> item) {
    // 从 item 中提取摘要信息
    final gnssPoints = item['gn'] as List<dynamic>? ?? [];
    final pointCount = gnssPoints.length;
    final batteryLevel = item['el'] ?? 'N/A';
    final hdop = item['HDOP']?.toStringAsFixed(1) ?? 'N/A';
    final vdop = item['VDOP']?.toStringAsFixed(1) ?? 'N/A';
    final timestamp = item['t'] != null
        ? DateTime.fromMillisecondsSinceEpoch(item['t'] * 1000)
        : null;

    // 格式化JSON用于显示
    const jsonEncoder = JsonEncoder.withIndent('  ');
    final prettyJson = jsonEncoder.convert(item);

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 6.0),
      child: ExpansionTile(
        leading: const Icon(Icons.cloud_done_outlined, color: Colors.green),
        title: Text(
          '上传成功 (含 $pointCount 个点)',
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        subtitle: Text(
          '时间: ${timestamp != null ? DateFormat('HH:mm:ss').format(timestamp) : 'N/A'} | ' 
          '电量: $batteryLevel% | ' 
          '精度(H/V): $hdop/$vdop',
        ),
        children: [
          Container(
            color: Colors.black.withOpacity(0.05),
            padding: const EdgeInsets.all(12.0),
            alignment: Alignment.centerLeft,
            child: SelectableText(
              prettyJson,
              style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
            ),
          )
        ],
      ),
    );
  }

  void _showClearConfirmationDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('确认操作'),
        content: const Text('确定要清空所有MQTT上传历史记录吗？此操作不可恢复。'),
        actions: <Widget>[
          TextButton(
            child: const Text('取消'),
            onPressed: () => Get.back(),
          ),
          TextButton(
            child: const Text('全部清空'),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            onPressed: () {
              controller.clearHistory();
              Get.back();
            },
          ),
        ],
      ),
    );
  }
}
